package com.songlanyun.modules.celebrity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.enums.ApplyNetRedConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.BeanUtil;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.celebrity.dao.UserApplyNetRedDao;
import com.songlanyun.modules.celebrity.entity.UserApplyNetRed;
import com.songlanyun.modules.celebrity.model.UserApplyNetRedCheckDTO;
import com.songlanyun.modules.celebrity.model.UserApplyNetRedDTO;
import com.songlanyun.modules.celebrity.model.UserApplyNetRedVO;
import com.songlanyun.modules.celebrity.service.UserApplyNetRedService;
import com.songlanyun.modules.exception.MemberException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;


@Service("userApplyNetRedService")
public class UserApplyNetRedServiceImpl extends ServiceImpl<UserApplyNetRedDao, UserApplyNetRed> implements UserApplyNetRedService {

    @Autowired
    private AccountService accountService;

    @Override
    public UserApplyNetRedVO queryOneById(Long id) {
        UserApplyNetRedVO userApplyNetRedVO =
                this.baseMapper.selectOneById(id);
        return userApplyNetRedVO;
    }

    @Override
    public UserApplyNetRedVO queryOneByUserId(Long userId) {
        UserApplyNetRedVO userApplyNetRedVO =
                this.baseMapper.selectLatestOneByUserId(userId);
        return userApplyNetRedVO;
    }

    @Override
    public UserApplyNetRed loadLatestOneByUserId(Long userId) {

        UserApplyNetRed obj = this.getOne(new LambdaQueryWrapper<UserApplyNetRed>()
                .eq(UserApplyNetRed::getUserId, userId)
                .orderByDesc(UserApplyNetRed::getCreateTime)
                .last("limit 1"));
        return obj;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserApplyNetRedVO> page =
                this.baseMapper.selectApplyNetRedVOPage(new Query<UserApplyNetRed>().getPage(params), params);
        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserApplyNetRed check(UserApplyNetRedCheckDTO dto) {
        ValidatorUtils.validateEntity(dto);
        if (dto.getState() == null) {
            throw new RRException("审核状态不能为空");
        }
        UserApplyNetRed entity = this.getById(dto.getId());
        if (entity == null) {
            throw new RRException(MemberException.NET_RED_APPLY_NOT_EXIST);
        }
        ApplyNetRedConstant.StateEnum state = entity.getState();
        switch (state) {
            case PASS:
            case FAIL:
                throw new RRException(MemberException.NET_RED_APPLY_CHECK_AGAIN);
            default:
                break;
        }
        entity.setState(ApplyNetRedConstant.StateEnum.getByCode(dto.getState()));
        entity.setCheckTime(new Date());
        if (ApplyNetRedConstant.StateEnum.FAIL.equals(entity.getState())) {
            entity.setReason(dto.getReason());
        }
        this.baseMapper.updateById(entity);

        if (ApplyNetRedConstant.StateEnum.PASS.equals(entity.getState())) {
            /**
             * 如果审核通过,会员具有网红身份
             */
            AccountEntity account = accountService.getUserById(entity.getUserId(), true);
            account.setIsCelebrity(Boolean.TRUE);
            accountService.modify(account);
        }

        return entity;
    }

    @Override
    public UserApplyNetRed addEntity(Long userId, UserApplyNetRedDTO dto) {
        ValidatorUtils.validateEntity(dto);
        UserApplyNetRed userApplyNetRed = this.loadLatestOneByUserId(userId);
        if (userApplyNetRed != null) {
            ApplyNetRedConstant.StateEnum state = userApplyNetRed.getState();
            switch (state) {
                case PASS:
                    throw new RRException(MemberException.NET_RED_APPLY_PASS);
                case WAIT:
                    throw new RRException(MemberException.NET_RED_APPLY_WAIT);
                default:
                    break;
            }
        }
        UserApplyNetRed entity = new UserApplyNetRed();
        //保存
        BeanUtil.copyPropertiesIgnoreNull(dto, entity);//克隆一份
        entity.setUserId(userId);
        entity.setState(ApplyNetRedConstant.StateEnum.WAIT);
        /**
         * 保存 平台类型 粉丝量级 内容方向
         */
        entity.setPlatformKey(dto.getPlatform().getPlatformKey());
        entity.setPlatformValue(dto.getPlatform().getPlatformValue());
        entity.setFanweightKey(ApplyNetRedConstant.FanweightEnum.getByCode(dto.getFanweight().getFanweightKey()));
        entity.setFanweightValue(dto.getFanweight().getFanweightValue());
        entity.setContentDirectionKey(dto.getContentDirection().getContentDirectionKey());
        entity.setContentDirectionValue(dto.getContentDirection().getContentDirectionValue());

        this.save(entity);
        return entity;
    }

}
